from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from celery_tasks.static_html.tasks import get_detail_html
from goods.models import SKUImage, SKU


class ImageSerializer(serializers.ModelSerializer):
    """
        商品图片序列化器
    """
    # 返回图片关联的sku的id值  关联对象嵌套序列化返回
    sku = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = SKUImage
        fields = ('sku', 'id', 'image')

    def create(self, validated_data):
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取图片数据   在序列化器中获取request对象
        request = self.context['request']
        image_file = request.data.get('image')
        # 上传图片
        res = client.upload_by_buffer(image_file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 获取上传后的路径
        image_url = res['Remote file_id']
        # 获取sku_id
        sku_id = request.data.get['sku']
        # 保存图片
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 详情页静态化处理
        # 获取sku对象
        sku=SKU.objects.get(id=request.data['sku'])
        if not sku.default_image:
            # 没有默认图片
            sku.default_image=image_url
            sku.save()
        # 异步生成静态化页面
        get_detail_html.delay(request.data['sku'])
        return img

    def update(self, instance, validated_data):
        # 建立FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取图片数据 在序列化器中获取request对象
        request = self.context['request']
        image_file = request.data.get('image')
        # 上传图片
        res = client.upload_by_buffer(image_file.read())
        # 判断返回结果
        if res['Status'] !='Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        # 上传成功将返回的文件路径更新到图片表中
        image_url=res['Remote file_id']
        instance.image=image_url
        instance.sku_id=request.data['sku']
        instance.save()
        # 返回保存后的图片对象数据
        return instance


class SKUSerializer(serializers.ModelSerializer):
    """
    sku商品序列化器
    """

    class Meta:
        model = SKU
        fields = ('id', 'name')
